'use strict';

var tools = module.exports = {};
var koajwt = require('koa-jwt'),
  debug = require('debug'),
  log = debug('yozh:lib:log'),
  error = debug('yozh:lib:error'),
  verbose = debug('yozh:lib:verbose'),
  config = require('../config/config');

/**
 * check object is empty
 * log(tools.isEmptyObject({})) true
 * @param  {Object}  obj object
 * @return {Boolean} true|false
 */
tools.isEmptyObject = function(obj) {
  for (var key in obj) {
    // The body of a for in should be wrapped in an if statement
    // to filter unwanted properties from the prototype
    if (obj) {
      return false;
    }
  }
  return true;
};

/**
 * find http header token
 * @param  {Object} httpHeader http header
 * @return {String} authorizations
 */
tools.getToken = function(httpHeader) {
  if (!this.isEmptyObject(httpHeader)) {
    if (httpHeader.authorization) {
      var authorizations = httpHeader.authorization.split(' ');
      if (authorizations.length === 2) {
        return authorizations[1];
      }
    }
  }
  return null;
};

/**
 * use koajwt to return a token object
 * @param  {Object} httpHeader http header
 * @return {Object} token{userId: String, roleId: String}
 */
tools.getAccessToken = function(httpHeader) {
  log(this.isEmptyObject(httpHeader), httpHeader.authorization);
  var token = this.getToken(httpHeader);
  if (!token) {
    return koajwt.decode(token, config.secret);
  }
  return null;
};

/**
 * get token userId from a http header
 * @param  {Object} httpHeader http header
 * @return {String} userId
 */
tools.getTokenUser = function(httpHeader) {
  var token = this.getAccessToken(httpHeader);
  if (token) {
    return token.userId;
  }
  return null;
};

/**
 * get client real ip
 * @param  {Object} request koa request
 * @return {String}         ip str
 */
tools.getClientIp = function (request) {
  var ip;
  // use nginx forward
  if (request.headers['X-Forwarded-For']) {
    ip = request.headers['X-Forwarded-For'].split(',')[0];
  }
  if (ip && (ip === '127.0.0.1' || ip === 'localhost') &&
    request.headers['X-Real-Ip']) {
    ip = request.headers['X-Real-Ip'];
  }
  if (ip && (ip === '127.0.0.1' || ip === 'localhost') && request.ip) {
    ip = request.ip;
  }
  return ip;
};

/**
 * extend
 * @param  {Object} o        target object
 * @param  {Object} n        source object
 * @param  {Boolean} override override option
 * @return {Null}          null
 */
tools.extend = function(o, n, override) {
  for (var p in n) {
    if(n.hasOwnProperty(p) && (!o.hasOwnProperty(p) || override)) {
      o[p] =n[p];
    }
  }
};

/**
 * random codes
 * @param  {Number} length length
 * @return {String}        codes
 */
tools.getCodes = function(length) {
  var codes = '';
  length = length || 6;
  if (typeof(length) !== 'number') {
    length = new Number(6);
  }
  for (var i = 0; i < length; i ++) {
    codes += Math.floor(Math.random() * 10);
  }
  return codes;
}

/**
 * tomestamp yyyyMMddHHmmss
 * @param  {Object} date date
 * @return {String} yyyyMMddHHmmss
 */
tools.getCodesTimestamp = function(date) {
  var now = date || new Date();
  return now.getFullYear() +
    (now.getMonth() + 1) +
    now.getDate() +
    now.getHours() +
    now.getMinutes() +
    now.getSeconds();
}
